<template>
  <div class="lessons-page">
    <!-- 简洁页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>课程管理</h1>
        <span class="total-count">共 {{ lessonStore.pagination.total }} 个课程</span>
      </div>
      <div class="header-right">
        <div class="search-container">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入课程标题进行搜索..."
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
            class="search-input"
            size="large"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
            <template #append>
              <el-button 
                @click="handleSearch" 
                :loading="lessonStore.isLoading"
                type="primary"
                class="search-btn"
              >
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        <el-button type="primary" @click="openCreateDialog" size="large" class="add-btn">
          <el-icon><Plus /></el-icon>
          添加课程
        </el-button>
      </div>
    </div>

    <!-- 优化表格容器 -->
    <div class="table-container">
      <div class="table-header" v-if="selectedIds.length > 0">
        <div class="table-title">
          <span>已选择 {{ selectedIds.length }} 项</span>
        </div>
        <div class="table-actions">
          <el-button
            type="danger"
            size="small"
            @click="handleBatchDelete"
            class="batch-btn"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <el-table
          :data="lessonStore.lessons"
          v-loading="lessonStore.isLoading"
          @selection-change="handleSelectionChange"
          row-key="id"
          stripe
          height="500"
          :scrollbar-always-on="true"
          class="data-table"
        >
          <el-table-column type="selection" width="50" />
          
          <el-table-column label="序列" width="80" type="index" :index="(index: number) => (searchForm.page - 1) * searchForm.limit + index + 1" />
          
          <el-table-column label="封面" width="100">
            <template #default="{ row }">
              <div class="cover-preview">
                <div v-if="row.coverImage" class="cover-image-wrapper">
                  <img 
                    :src="getImageUrl(row.coverImage)" 
                    :alt="row.title"
                    class="cover-thumbnail"
                    @error="handleImageError"
                    @click="previewCoverImage(row)"
                  />
                  <div class="cover-overlay">
                    <el-icon class="preview-icon"><View /></el-icon>
                  </div>
                </div>
                <div v-else class="no-cover">
                  <el-icon><Picture /></el-icon>
                  <span>无封面</span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="课程标题" min-width="200">
            <template #default="{ row }">
              <div class="lesson-info">
                <div class="lesson-title">{{ row.title }}</div>
                <div class="lesson-slug">{{ row.slug }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.description || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="分类" width="120">
            <template #default="{ row }">
              {{ row.category?.name || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="难度" width="100">
            <template #default="{ row }">
              <el-tag :type="getDifficultyType(row.difficulty)" size="small">
                {{ getDifficultyText(row.difficulty) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="学习时长" width="100">
            <template #default="{ row }">
              {{ row.duration ? `${row.duration}分钟` : '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="浏览量" width="100">
            <template #default="{ row }">
              {{ row.viewCount || 0 }}
            </template>
          </el-table-column>
          
          <el-table-column label="点赞数" width="100">
            <template #default="{ row }">
              {{ row.likeCount || 0 }}
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-switch
                v-model="row.isPublished"
                @change="handleStatusChange(row)"
                size="small"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="推荐" width="80">
            <template #default="{ row }">
              <el-switch
                v-model="row.isFeatured"
                @change="handleFeaturedChange(row)"
                size="small"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="创建时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="success" link size="small" @click="handlePreview(row)">
                预览
              </el-button>
              <el-popconfirm
                title="确定删除吗？"
                @confirm="handleDelete(row.id)"
              >
                <template #reference>
                  <el-button type="danger" link size="small">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
        
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.limit"
          :total="lessonStore.pagination.total"
          :page-sizes="[20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          background
        />
      </div>
    </div>

    <!-- 简化的创建/编辑对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingLesson ? '编辑课程' : '创建课程'"
      width="800px"
      :before-close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="lesson-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入课程标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程标识" prop="slug">
              <el-input v-model="form.slug" placeholder="请输入课程标识">
                <template #append>
                  <el-button @click="handleGenerateSlug">生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select 
                v-model="form.categoryId" 
                placeholder="选择分类" 
                clearable 
                style="width: 100%"
                :loading="isLoadingCategories"
              >
                <el-option
                  v-for="category in flattenedCategories"
                  :key="category.id"
                  :label="category.indentName"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="选择难度" style="width: 100%">
                <el-option label="初级" value="beginner" />
                <el-option label="中级" value="intermediate" />
                <el-option label="高级" value="advanced" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="form.sortOrder"
            :min="0"
            :max="999"
            style="width: 100%"
            placeholder="请输入排序权重"
          />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入课程内容（Markdown格式）"
          />
        </el-form-item>

        <el-form-item label="摘要" prop="excerpt">
          <el-input
            v-model="form.excerpt"
            type="textarea"
            :rows="3"
            placeholder="请输入课程摘要"
          />
        </el-form-item>

        <el-form-item label="封面图" prop="coverImage">
          <div class="cover-upload-container">
            <ImageUpload
              v-model="form.coverImage"
              placeholder="点击上传封面图"
              hint="建议尺寸：800x450，支持 JPG、PNG、GIF、WebP 格式"
              width="200px"
              height="120px"
              alt="课程封面"
              @upload-success="handleCoverImageSuccess"
              @upload-error="handleCoverImageError"
            />
            <div class="upload-separator">或</div>
            <el-button 
              type="primary" 
              plain 
              @click="showImageSelector = true"
              :icon="Picture"
              size="small"
            >
              从图库选择
            </el-button>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习时长" prop="duration">
              <el-input-number
                v-model="form.duration"
                :min="1"
                :max="999"
                style="width: 100%"
                placeholder="请输入学习时长（分钟）"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="标签">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="SEO关键词" prop="metaKeywords">
              <el-input v-model="form.metaKeywords" placeholder="请输入SEO关键词，多个关键词用逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SEO描述" prop="metaDescription">
              <el-input
                v-model="form.metaDescription"
                type="textarea"
                :rows="2"
                placeholder="请输入SEO描述"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch
                v-model="form.isPublished"
                active-text="已发布"
                inactive-text="草稿"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐">
              <el-switch
                v-model="form.isFeatured"
                active-text="推荐"
                inactive-text="普通"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">
          {{ editingLesson ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 图片选择器 -->
    <ImageSelector
      v-model="showImageSelector"
      @select="handleImageSelect"
    />

    <!-- 封面图片预览对话框 -->
    <el-dialog
      v-model="showCoverPreview"
      title="封面预览"
      width="60%"
      append-to-body
    >
      <div class="cover-preview-dialog">
        <img
          v-if="previewCoverData && previewCoverData.coverImage"
          :src="getImageUrl(previewCoverData.coverImage)"
          :alt="previewCoverData.title"
          class="preview-cover-image"
        />
        <div class="preview-info">
          <h3>{{ previewCoverData?.title }}</h3>
          <p>{{ previewCoverData?.excerpt || '暂无简介' }}</p>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useLessonStore } from '@/stores/lesson'
import { useCategoryStore } from '@/stores/category'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Delete,
  Picture,
  View
} from '@element-plus/icons-vue'
import ImageUpload from '@/components/ImageUpload.vue'
import ImageSelector from '@/components/ImageSelector.vue'

import type { FormInstance, FormRules } from 'element-plus'
import type { Lesson, Category, CategoryWithIndent, LessonFormData, UploadFile } from '@/types/admin'
import { formatDate } from '@/utils/format'
import { getImagePreviewUrl, validateImageUrl } from '@/utils/upload'
import { config } from '@/config'

const router = useRouter()
const lessonStore = useLessonStore()
const categoryStore = useCategoryStore()

const showCreateDialog = ref(false)
const editingLesson = ref<Lesson | null>(null)
const isSubmitting = ref(false)
const selectedIds = ref<number[]>([])
const isLoadingCategories = ref(false)
const showImageSelector = ref(false)
const showCoverPreview = ref(false)
const previewCoverData = ref<Lesson | null>(null)


// 搜索表单
const searchForm = reactive({
  search: '',
  page: 1,
  limit: 20,
  categoryId: '',
  difficulty: '',
  isPublished: undefined as boolean | undefined
})

// 课程表单
const formRef = ref<FormInstance>()
const form = reactive({
  id: undefined as number | undefined,
  title: '',
  slug: '',
  categoryId: null as number | null,
  difficulty: 'beginner' as 'beginner' | 'intermediate' | 'advanced',
  content: '',
  excerpt: '',
  coverImage: '',
  duration: 0,
  sortOrder: 0,
  isPublished: false,
  isFeatured: false,
  author: '',
  metaKeywords: '',
  metaDescription: '',
  tags: [] as string[]
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入课程标题', trigger: 'blur' },
    { min: 2, max: 200, message: '课程标题长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入课程标识', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '标识只能包含小写字母、数字和连字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入课程内容', trigger: 'blur' }
  ],
  excerpt: [
    { max: 1000, message: '摘要不能超过1000字符', trigger: 'blur' }
  ],
  coverImage: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && !validateImageUrl(value)) {
          callback(new Error('封面图片URL格式无效'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  duration: [
    { type: 'number', min: 1, message: '学习时长必须是正整数', trigger: 'blur' }
  ],
  author: [
    { max: 100, message: '作者名称不能超过100字符', trigger: 'blur' }
  ],
  metaKeywords: [
    { max: 255, message: 'SEO关键词不能超过255字符', trigger: 'blur' }
  ],
  metaDescription: [
    { max: 255, message: 'SEO描述不能超过255字符', trigger: 'blur' }
  ]
}

// 获取分类列表
const categories = ref<Category[]>([])
const loadCategories = async () => {
  if (isLoadingCategories.value) return
  
  try {
    isLoadingCategories.value = true
    await categoryStore.fetchCategoryTree()
    categories.value = categoryStore.categoryTree
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    isLoadingCategories.value = false
  }
}

// 将树形结构扁平化为列表
const flattenCategoryTree = (tree: Category[]): CategoryWithIndent[] => {
  const result: CategoryWithIndent[] = []
  
  const traverse = (nodes: Category[], level = 0) => {
    nodes.forEach(node => {
      result.push({
        ...node,
        level,
        indentName: '　'.repeat(level) + node.name
      })
      
      if (node.children && node.children.length > 0) {
        traverse(node.children, level + 1)
      }
    })
  }
  
  traverse(tree)
  return result
}

// 获取扁平化的分类列表
const flattenedCategories = computed(() => {
  return flattenCategoryTree(categories.value)
})

// 处理搜索
const handleSearch = () => {
  searchForm.page = 1
  loadData()
}

// 加载数据
const loadData = () => {
  const params: any = {
    page: searchForm.page,
    limit: searchForm.limit
  }
  
  if (searchForm.search?.trim()) params.search = searchForm.search.trim()
  if (searchForm.categoryId) params.categoryId = searchForm.categoryId
  if (searchForm.difficulty) params.difficulty = searchForm.difficulty
  if (searchForm.isPublished !== undefined) params.isPublished = searchForm.isPublished
  
  lessonStore.fetchLessons(params)
}

// 处理页码变化
const handlePageChange = (page: number) => {
  searchForm.page = page
  loadData()
}

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  searchForm.limit = size
  searchForm.page = 1
  loadData()
}

// 处理选择变化
const handleSelectionChange = (selection: Lesson[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 处理状态切换
const handleStatusChange = async (lesson: Lesson) => {
  try {
    await lessonStore.toggleLessonPublishStatus(lesson.id, lesson.isPublished)
  } catch (error) {
    lesson.isPublished = !lesson.isPublished
  }
}

// 处理推荐状态切换
const handleFeaturedChange = async (lesson: Lesson) => {
  try {
    await lessonStore.toggleLessonFeaturedStatus(lesson.id, lesson.isFeatured)
  } catch (error) {
    lesson.isFeatured = !lesson.isFeatured
  }
}

// 打开创建对话框
const openCreateDialog = async () => {
  await loadCategories()
  showCreateDialog.value = true
}

// 编辑课程
const handleEdit = async (lesson: Lesson) => {
  await loadCategories()
  
  editingLesson.value = lesson
  Object.assign(form, {
    id: lesson.id,
    title: lesson.title,
    slug: lesson.slug,
    categoryId: lesson.categoryId,
    difficulty: lesson.difficulty,
    content: lesson.content,
    excerpt: lesson.excerpt || '',
    coverImage: lesson.coverImage || '',
    duration: lesson.duration || 0,
    sortOrder: lesson.sortOrder || 0,
    isPublished: lesson.isPublished,
    isFeatured: lesson.isFeatured,
    author: lesson.author || '',
    metaKeywords: lesson.metaKeywords || '',
    metaDescription: lesson.metaDescription || '',
    tags: lesson.tags?.map(tag => tag.name) || []
  })
  showCreateDialog.value = true
}

// 预览课程
const handlePreview = (lesson: Lesson) => {
  window.open(`/lessons/${lesson.slug}`, '_blank')
}

// 处理删除
const handleDelete = async (id: number) => {
  try {
    await lessonStore.deleteLesson(id)
    if (lessonStore.lessons.length === 1 && searchForm.page > 1) {
      searchForm.page -= 1
    }
    loadData()
  } catch (error) {
    // 错误已在store中处理
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个课程吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const deleteCount = selectedIds.value.length
    await lessonStore.deleteLessonsBatch(selectedIds.value)
    selectedIds.value = []
    
    if (lessonStore.lessons.length <= deleteCount && searchForm.page > 1) {
      searchForm.page -= 1
    }
    loadData()
  } catch {
    // 用户取消
  }
}

// 生成 slug 的函数
const generateSlug = (title: string): string => {
  if (!title || !title.trim()) {
    return `lesson-${Date.now()}`
  }
  
  // 转换为小写
  let slug = title.toLowerCase()
  // 替换空格为连字符
  slug = slug.replace(/\s+/g, '-')
  // 移除特殊字符，保留中文字符
  slug = slug.replace(/[^a-z0-9\u4e00-\u9fa5-]/g, '')
  // 移除连续的连字符
  slug = slug.replace(/-+/g, '-')
  // 移除首尾连字符
  slug = slug.replace(/^-+|-+$/g, '')
  
  // 如果处理后为空，使用默认值
  if (!slug) {
    slug = 'lesson'
  }
  
  // 确保不以连字符开头
  if (slug.startsWith('-')) {
    slug = slug.substring(1)
  }
  
  // 添加时间戳确保唯一性
  const timestamp = Date.now().toString().slice(-6)
  return `${slug}-${timestamp}`
}

// 监听标题变化，自动生成 slug
watch(() => form.title, (newTitle) => {
  if (newTitle && !form.slug) {
    form.slug = generateSlug(newTitle)
  }
})

// 手动生成 slug
const handleGenerateSlug = () => {
  if (form.title) {
    form.slug = generateSlug(form.title)
  } else {
    ElMessage.warning('请先输入课程标题')
  }
}

// 关闭对话框
const closeDialog = () => {
  showCreateDialog.value = false
  editingLesson.value = null
  formRef.value?.resetFields()
  Object.assign(form, {
    id: undefined,
    title: '',
    slug: '',
    categoryId: null,
    difficulty: 'beginner',
    content: '',
    excerpt: '',
    coverImage: '',
    duration: 0,
    sortOrder: 0,
    isPublished: false,
    isFeatured: false,
    author: '',
    metaKeywords: '',
    metaDescription: '',
    tags: []
  })
}

// 修改表单提交逻辑
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 确保有 slug
    if (!form.slug) {
      if (form.title) {
        form.slug = generateSlug(form.title)
      } else {
        ElMessage.error('请提供课程标题或标识')
        return
      }
    }
    
    // 构建表单数据 - 只包含有效字段
    const formData: any = {}
    
    // 必填字段验证
    if (!form.title?.trim()) {
      ElMessage.error('课程标题不能为空')
      return
    }
    if (!form.slug?.trim()) {
      ElMessage.error('课程标识不能为空')
      return
    }
    
    // 验证slug格式
    const slugPattern = /^[a-z0-9\u4e00-\u9fa5][a-z0-9\u4e00-\u9fa5-]*[a-z0-9\u4e00-\u9fa5]$|^[a-z0-9\u4e00-\u9fa5]$/
    if (!slugPattern.test(form.slug.trim())) {
      ElMessage.error('课程标识格式无效，不能以连字符开头或结尾')
      // 自动修复slug
      form.slug = generateSlug(form.title)
      ElMessage.info(`已自动修正为: ${form.slug}`)
    }
    if (!form.categoryId || Number(form.categoryId) <= 0) {
      ElMessage.error('请选择有效的课程分类')
      return
    }
    if (!form.difficulty) {
      ElMessage.error('请选择课程难度')
      return
    }
    if (!form.content?.trim()) {
      ElMessage.error('课程内容不能为空')
      return
    }
    
    // 设置必填字段
    formData.title = form.title.trim()
    formData.slug = form.slug.trim()
    formData.categoryId = Number(form.categoryId)
    formData.difficulty = form.difficulty
    formData.content = form.content.trim()
    
    // 可选字段 - 只有当有值时才添加
    if (form.duration && Number(form.duration) > 0) {
      formData.duration = Number(form.duration)
    }
    
    formData.sortOrder = Number(form.sortOrder) || 0
    formData.isPublished = Boolean(form.isPublished)
    formData.isFeatured = Boolean(form.isFeatured)
    
    // 处理标签
    if (Array.isArray(form.tags)) {
      const validTags = form.tags.filter(tag => tag && tag.trim())
      if (validTags.length > 0) {
        formData.tags = validTags
      } else {
        formData.tags = []
      }
    } else {
      formData.tags = []
    }
    
    // 可选文本字段
    if (form.excerpt?.trim()) {
      formData.excerpt = form.excerpt.trim()
    }
    if (form.author?.trim()) {
      formData.author = form.author.trim()
    }
    if (form.metaKeywords?.trim()) {
      formData.metaKeywords = form.metaKeywords.trim()
    }
    if (form.metaDescription?.trim()) {
      formData.metaDescription = form.metaDescription.trim()
    }
    
    // 处理封面图片字段
    if (form.coverImage?.trim()) {
      let coverImageUrl = form.coverImage.trim()
      
      // 开发环境下，如果是相对路径，保持相对路径
      if (import.meta.env.DEV && coverImageUrl.startsWith('/uploads/')) {
        formData.coverImage = coverImageUrl
      } else if (coverImageUrl.startsWith('/uploads/')) {
        // 生产环境转换为完整URL
        coverImageUrl = `${config.uploadBaseUrl}${coverImageUrl}`
        formData.coverImage = coverImageUrl
      } else {
        // 已经是完整URL或其他格式
        formData.coverImage = coverImageUrl
      }
    }
    
    console.log('提交的表单数据:', formData)
    console.log('封面图片URL:', formData.coverImage)
    console.log('表单数据详细信息:', {
      hasTitle: !!formData.title,
      hasSlug: !!formData.slug,
      hasCategoryId: !!formData.categoryId,
      hasDifficulty: !!formData.difficulty,
      hasContent: !!formData.content,
      titleLength: formData.title?.length,
      slugLength: formData.slug?.length,
      contentLength: formData.content?.length,
      categoryIdType: typeof formData.categoryId,
      categoryIdValue: formData.categoryId,
      tagsLength: formData.tags?.length,
      tagsContent: formData.tags
    })
    
    isSubmitting.value = true
    
    if (form.id) {
      // 更新课程
      await lessonStore.updateLesson(form.id, formData)
      ElMessage.success('课程更新成功')
    } else {
      // 创建课程
      await lessonStore.createLesson(formData)
      ElMessage.success('课程创建成功')
    }
    
    closeDialog()
    loadData()
  } catch (error: any) {
    console.error('提交失败:', error)
    
    // 处理不同类型的错误
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 400:
          // 处理验证错误
          console.log('400错误详情:', data)
          if (data.details && Array.isArray(data.details)) {
            const errorMessages = data.details.map((detail: any) => {
              // 特殊处理封面图片错误
              if (detail.path === 'coverImage' || detail.msg?.includes('封面图片')) {
                return '封面图片URL格式无效，请重新上传图片'
              }
              return detail.msg || detail.message
            }).join('\n')
            ElMessage.error(errorMessages)
          } else if (data.error) {
            ElMessage.error(data.error)
          } else if (data.message) {
            ElMessage.error(data.message)
          } else {
            ElMessage.error('请求参数错误，请检查表单数据')
          }
          break
          
        case 409:
          // 处理 slug 冲突
          if (form.title) {
            form.slug = generateSlug(form.title)
            ElMessage.warning('课程标识已存在，已自动生成新的标识')
            handleSubmit() // 重试提交
          } else {
            ElMessage.error('课程标识已存在，请修改后重试')
          }
          break
          
        case 401:
          ElMessage.error('请先登录')
          break
          
        case 403:
          ElMessage.error('没有权限执行此操作')
          break
          
        default:
          ElMessage.error(data.message || '操作失败，请重试')
      }
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接')
    } else {
      ElMessage.error(error.message || '操作失败，请重试')
    }
  } finally {
    isSubmitting.value = false
  }
}

// 获取难度类型
const getDifficultyType = (difficulty: string) => {
  const types: Record<string, string> = {
    beginner: 'success',
    intermediate: 'warning',
    advanced: 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  const texts: Record<string, string> = {
    beginner: '初级',
    intermediate: '中级',
    advanced: '高级'
  }
  return texts[difficulty] || difficulty
}

// 在 script setup 中添加
const availableTags = ref<string[]>([])

// 处理封面图片上传成功
const handleCoverImageSuccess = (url: string) => {
  console.log('封面图片上传成功，接收到的URL:', url)
  
  // 验证URL格式
  if (!validateImageUrl(url)) {
    console.error('接收到的URL格式无效:', url)
    ElMessage.error('图片URL格式无效，请重新上传')
    return
  }
  
  form.coverImage = url
  console.log('表单中的封面图片URL已更新:', form.coverImage)
  ElMessage.success('封面图片上传成功')
}

// 处理封面图片上传失败
const handleCoverImageError = (error: string) => {
  console.error('封面图片上传失败:', error)
  ElMessage.error(`封面图片上传失败: ${error}`)
}

// 处理从图库选择图片
const handleImageSelect = (image: UploadFile) => {
  console.log('从图库选择图片:', image)
  
  // 验证URL格式
  if (!validateImageUrl(image.url)) {
    console.error('选择的图片URL格式无效:', image.url)
    ElMessage.error('选择的图片URL格式无效')
    return
  }
  
  form.coverImage = image.url
  console.log('表单中的封面图片URL已更新:', form.coverImage)
  ElMessage.success(`已选择图片: ${image.filename}`)
}

// 预览封面图片
const previewCoverImage = (lesson: Lesson) => {
  previewCoverData.value = lesson
  showCoverPreview.value = true
}

// 修改获取图片URL的函数
const getImageUrl = (url: string) => {
  if (!url) return ''
  
  // 开发环境直接使用相对路径，让Vite代理处理
  if (import.meta.env.DEV) {
    // 如果是完整URL，提取路径部分
    if (url.startsWith('http://') || url.startsWith('https://')) {
      try {
        const urlObj = new URL(url)
        return urlObj.pathname
      } catch {
        return url
      }
    }
    // 相对路径直接返回
    return url.startsWith('/') ? url : '/' + url
  }
  
  // 生产环境使用完整URL
  return getImagePreviewUrl(url)
}

// 优化图片错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  const originalSrc = img.src
  
  console.warn('图片加载失败:', originalSrc)
  
  // 如果还没有重试过
  if (!img.dataset.retried) {
    img.dataset.retried = 'true'
    
    // 尝试不同的URL格式
    if (originalSrc.includes('localhost:5173')) {
      // 如果包含错误的端口，修正为正确的路径
      const pathMatch = originalSrc.match(/\/uploads\/.*$/)
      if (pathMatch) {
        img.src = pathMatch[0]
        return
      }
    }
    
    // 尝试添加 /uploads 前缀（如果没有的话）
    if (!originalSrc.includes('/uploads/')) {
      img.src = `/uploads/images/${originalSrc.split('/').pop()}`
      return
    }
  }
  
  // 最终失败，显示错误状态
  const wrapper = img.closest('.cover-image-wrapper')
  if (wrapper) {
    wrapper.innerHTML = `
      <div class="error-cover">
        <i class="el-icon">
          <svg viewBox="0 0 1024 1024" width="16" height="16">
            <path fill="currentColor" d="M160 144h704a32 32 0 0 1 32 32v672a32 32 0 0 1-32 32H160a32 32 0 0 1-32-32V176a32 32 0 0 1 32-32zm0 64v672h704V208H160zm64 128h192v64H224v-64zm0 192h192v64H224v-64zm448-192a96 96 0 1 1 0 192 96 96 0 0 1 0-192zm0 64a32 32 0 1 0 0 64 32 32 0 0 0 0-64z"/>
          </svg>
        </i>
        <span>加载失败</span>
      </div>
    `
  }
}

// 添加网络状态检查
const checkNetworkStatus = () => {
  if (!navigator.onLine) {
    ElMessage.error('网络连接已断开，请检查网络设置')
    return false
  }
  return true
}

// 在组件挂载时检查网络状态
onMounted(() => {
  if (checkNetworkStatus()) {
    loadData()
  }
  
  // 监听网络状态变化
  window.addEventListener('online', () => {
    ElMessage.success('网络连接已恢复')
    loadData()
  })
  
  window.addEventListener('offline', () => {
    ElMessage.warning('网络连接已断开')
  })
})
</script>

<style scoped>
.lessons-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.total-count {
  margin-left: 12px;
  color: #666;
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-container {
  position: relative;
}

.search-input {
  width: 280px;
  transition: all 0.3s ease;
}

.search-input:focus-within {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.search-icon {
  color: #909399;
  transition: color 0.3s ease;
}

.search-input:focus-within .search-icon {
  color: #409EFF;
}

.search-btn {
  border-radius: 0 6px 6px 0;
  border-left: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.search-btn:hover {
  background: linear-gradient(135deg, #66b1ff, #409eff);
}

.add-btn {
  border-radius: 8px;
  padding: 12px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, #fff3cd, #ffeaa7);
  border-bottom: 1px solid #f0c36d;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #856404;
}

.table-actions {
  display: flex;
  align-items: center;
}

.batch-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  border: none;
  border-radius: 6px;
  color: white;
  transition: all 0.3s ease;
}

.batch-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.table-wrapper {
  position: relative;
  overflow: hidden;
}

.data-table {
  border-radius: 0;
}

.data-table :deep(.el-table__header-wrapper) {
  background: #fafbfc;
}

.data-table :deep(.el-table__header th) {
  background: #fafbfc;
  color: #495057;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
  padding: 12px 0;
}

.data-table :deep(.el-table__body-wrapper) {
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

.data-table :deep(.el-table__row) {
  transition: all 0.2s ease;
}

.data-table :deep(.el-table__row:hover) {
  background: #f8f9fa;
  transform: scale(1.001);
}

.lesson-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.lesson-title {
  font-weight: 500;
  color: #333;
}

.lesson-slug {
  font-size: 12px;
  color: #999;
}

.pagination {
  padding: 20px;
  text-align: right;
  background: #fafbfc;
  border-top: 1px solid #dee2e6;
}

.pagination :deep(.el-pagination) {
  gap: 8px;
}

.pagination :deep(.el-pager li) {
  border-radius: 6px;
  transition: all 0.2s ease;
}

.pagination :deep(.el-pager li:hover) {
  background: #409eff;
  color: white;
  transform: translateY(-1px);
}

.pagination :deep(.el-pagination__jump) {
  margin-left: 16px;
}

.pagination :deep(.el-select) {
  border-radius: 6px;
}

/* 响应式 */
@media (max-width: 768px) {
  .lessons-page {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .header-right {
    flex-direction: column;
    gap: 12px;
  }
  
  .header-right .el-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
}

.lesson-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 20px;
}

.lesson-form :deep(.el-form-item__label) {
  font-weight: 500;
}

.lesson-form :deep(.el-input-number) {
  width: 100%;
}

.lesson-form :deep(.el-select) {
  width: 100%;
}

.lesson-form :deep(.el-textarea__inner) {
  font-family: monospace;
}

.cover-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 50px;
}

.cover-image-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.cover-image-wrapper:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.cover-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 4px;
}

.cover-image-wrapper:hover .cover-overlay {
  opacity: 1;
}

.preview-icon {
  color: white;
  font-size: 18px;
}

.no-cover {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  color: #c0c4cc;
  font-size: 12px;
  gap: 4px;
}

.no-cover .el-icon {
  font-size: 16px;
}

.error-cover {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #fef0f0;
  border: 1px dashed #f56c6c;
  border-radius: 4px;
  color: #f56c6c;
  font-size: 12px;
  gap: 4px;
}

.cover-upload-container {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.upload-separator {
  color: #909399;
  font-size: 14px;
  margin: 0 8px;
}

.cover-preview-dialog {
  text-align: center;
}

.preview-cover-image {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
  border-radius: 8px;
  margin-bottom: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.preview-info p {
  margin: 0;
  color: #606266;
  line-height: 1.5;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .cover-upload-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .upload-separator {
    text-align: center;
    margin: 8px 0;
  }
  
  .cover-preview {
    width: 60px;
    height: 40px;
  }
}

</style> 